package xin.printk.android.module.plan;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.AppCompatRatingBar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Date;

import xin.printk.android.BasicActivity;
import xin.printk.android.R;
import xin.printk.android.data.entity.Plan;
import xin.printk.android.utils.DateUtils;
import xin.printk.android.utils.LogUtils;

public class PlanDetailActivity extends BasicActivity implements PlanDetailContract.View {

    private TextView mPlanTitle;
    private TextView mPlanCreateTime;
    private TextView mPlanContent;
    private TextView mPlanLevel;
    private TextView mPlanTime;
    private TextView mPlanCompletedTime;
    private FloatingActionButton mOkFAB;
    private FloatingActionButton mDeleteFAB;

    private ConstraintLayout mCommentLayout;
    private TextView mPlanResult;
    private AppCompatRatingBar mRatingBar;
    private TextView mComment;

    private Plan mPlan;
    private int mPlanId;

    private boolean isFirstLunch = true;
    private boolean isUpdate = false;
    private boolean isDone = false;
    private boolean isDelete = false;

    private int oldStatus;
    private int newStatus;

    private static final int REQUEST_CODE = 0x2000;

    public static final int DELETE_RESPONSE_CODE = 100;
    public static final int UPDATE_RESPONSE_CODE = 200;
    public static final int STATUS_CHANGE_RESPONSE_CODE = 300;

    private PlanDetailContract.Presenter mPresenter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_plan_detail);
        setToolbar(R.id.plan_detail_toolbar);
        setCanFinish(true);

        mPresenter = new PlanDetailPresenter(this);

        mPlanTitle = findViewById(R.id.tv_plan_title);
        mPlanCreateTime = findViewById(R.id.tv_plan_create_time);
        mPlanContent = findViewById(R.id.tv_plan_content);
        mPlanLevel = findViewById(R.id.tv_plan_level);
        mPlanTime = findViewById(R.id.tv_plan_time);
        mPlanCompletedTime = findViewById(R.id.tv_plan_complete_time);

        mCommentLayout = findViewById(R.id.cl_comment_layout);
        mPlanResult = findViewById(R.id.tv_plan_ret);
        mRatingBar = findViewById(R.id.rb_plan_rating);
        mComment = findViewById(R.id.tv_plan_comment);

        mOkFAB = findViewById(R.id.fab_ok);
        mOkFAB.setOnClickListener(mOkListener);
        mDeleteFAB = findViewById(R.id.fab_delete);
        mDeleteFAB.setOnClickListener(mDeleteListener);

        mLevelItems = getResources().getStringArray(R.array.plan_level);

        Intent intent = getIntent();
        if (intent != null) {
            mPlanId = intent.getIntExtra("plan_id", 0);
            mPresenter.getPlan();
        }
    }

    private View.OnClickListener mOkListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LogUtils.d("ok button click");
            showDoneDialog();
        }
    };

    private void showDoneDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_rating_comment, null, false);
        final AppCompatRatingBar ratingBar = view.findViewById(R.id.rb_plan_rating);
        final EditText commentText = view.findViewById(R.id.et_plan_comment);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.plan_add_comment);
        builder.setView(view);
        builder.setCancelable(false);
        builder.setPositiveButton(R.string.plan_comment, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                float rating = ratingBar.getRating();
                String comment = commentText.getText().toString();
                mPlan.setStatus(1);
                mPlan.setCompleteTime(DateUtils.dateToTimeStamp(new Date()));
                mPlan.setRating(rating);
                mPlan.setComment(comment);
                mPresenter.done();

            }
        });
        builder.setNegativeButton(R.string.cancel, null);
        builder.create().show();
    }

    private View.OnClickListener mDeleteListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LogUtils.d("delete button click");
            showDeleteDialog();
        }
    };

    private void showDeleteDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.plan_delete_msg);
        if (mPlan.getStatus() == 0) {
            builder.setMessage(R.string.plan_delete_undone_msg);
        } else {
            builder.setMessage(R.string.plan_delete_done_msg);
        }
        builder.setCancelable(false);
        builder.setPositiveButton(R.string.plan_delete, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mPresenter.delete();
            }
        });
        builder.setNegativeButton(R.string.cancel, null);
        builder.create().show();
    }

    private void updatePlan(Plan plan) {
        if (plan != null) {
            LogUtils.d("PlanDetailActivity updatePlan");
            int status = plan.getStatus();
            if (status == 0) {
                mCommentLayout.setVisibility(View.GONE);
                mOkFAB.show();
                mOkFAB.setVisibility(View.VISIBLE);
                mDeleteFAB.hide();
                mDeleteFAB.setVisibility(View.GONE);
                long diff = plan.getPlanTime() - DateUtils.dateToTimeStamp(new Date());
                long surplus = diff / 1000 / 60 / 60;
                String surplusTips;
                if (diff <= 0) {
                    surplus = Math.abs(surplus);
                    if (surplus > 24) {
                        surplusTips = getString(R.string.plan_over_completed_time) + (surplus / 24)
                                + getString(R.string.hour);
                    } else {
                        surplusTips = getString(R.string.plan_over_completed_time) + surplus
                                + getString(R.string.hour);
                    }
                    mPlanCompletedTime.setText(surplusTips);
                } else {
                    if (surplus > 24) {
                        surplusTips = getString(R.string.plan_away_from_completed_time) + (surplus / 24)
                                + getString(R.string.day);
                    } else {
                        surplusTips = getString(R.string.plan_away_from_completed_time) + surplus
                                + getString(R.string.hour);
                    }
                    mPlanCompletedTime.setText(surplusTips);
                }
                mPlanCompletedTime.setTextColor(getResources().getColor(R.color.red_dark));

                mPlanContent.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(PlanDetailActivity.this, EditPlanActivity.class);
                        intent.putExtra("plan_id", mPlan.getId());
                        startActivityForResult(intent, REQUEST_CODE);
                    }
                });
            } else {
                mCommentLayout.setVisibility(View.VISIBLE);
                long diff = plan.getCompleteTime() - plan.getPlanTime();

                String result;
                if (diff >= 0) {
                    result = getString(R.string.plan_result) + getString(R.string.plan_result_over_time);
                    mPlanResult.setTextColor(getResources().getColor(R.color.red_light));
                } else {
                    result = getString(R.string.plan_result) + getString(R.string.plan_result_in_time);
                    mPlanResult.setTextColor(getResources().getColor(R.color.green_light));
                }
                mPlanResult.setText(result);

                mRatingBar.setRating(plan.getRating());
                if (plan.getComment().isEmpty()){
                    mComment.setText(R.string.plan_no_comment);
                }else {
                    mComment.setText(plan.getComment());
                }

                mOkFAB.hide();
                mOkFAB.setVisibility(View.GONE);
                mDeleteFAB.show();
                mDeleteFAB.setVisibility(View.VISIBLE);
                String real_completed_time = getString(R.string.plan_real_completed_time)
                        + DateUtils.timeStampToDate(plan.getCompleteTime());
                mPlanCompletedTime.setText(real_completed_time);
                mPlanCompletedTime.setTextColor(getResources().getColor(R.color.green_dark));

                mPlanContent.setOnClickListener(null);
            }
            mPlanTitle.setText(plan.getTitle());
            String create = getString(R.string.plan_create_time)
                    + DateUtils.timeStampToDate(plan.getCreateTime());
            mPlanCreateTime.setText(create);
            mPlanContent.setText(plan.getContent());
            String level = getString(R.string.plan_level) + mLevelItems[mPlan.getLevel()];
            mPlanLevel.setText(level);
            mPlanLevel.setTextColor(getResources().getColor(mLevelColorResId[mPlan.getLevel()]));
            String planTime = getString(R.string.plan_completed_time) + DateUtils.timeStampToDate(plan.getPlanTime());
            mPlanTime.setText(planTime);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtils.d("PlanDetailActivity requestCode=" + requestCode + " resultCode=" + resultCode);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
            mPresenter.getPlan();
            isUpdate = true;
        }
    }

    @Override
    public Context getContext() {
        return getApplicationContext();
    }

    @Override
    public int getPlanId() {
        return mPlanId;
    }

    @Override
    public Plan getPlan() {
        return mPlan;
    }

    @Override
    public void notifyUpdate(Plan plan) {
        if (isFirstLunch) {
            oldStatus = plan.getStatus();
            isFirstLunch = false;
        } else {
            newStatus = plan.getStatus();
            if ((oldStatus ^ newStatus) == 1) {
                isDone = true;
            }
        }
        mPlan = plan;
        updatePlan(plan);
    }

    @Override
    public void showError(String message) {
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
    }

    @Override
    public void delete() {
        isDelete = true;
        finish();
    }

    @Override
    public void finish() {
        if (isDelete) {
            setResult(DELETE_RESPONSE_CODE);
        } else if (isDone) {
            setResult(STATUS_CHANGE_RESPONSE_CODE);
        } else if (isUpdate) {
            setResult(UPDATE_RESPONSE_CODE);
        }
        super.finish();
    }
}
